package com.uenpay.im.ui.old.activity.label;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.weight.view.MyGridView;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.contacts.ChooseContactsActivity;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.util.app.base.BaseActivity;

import java.util.ArrayList;

/**
 * @author SL
 * @created 2015-12-28 12:09:32
 * @copyRight http://www.qiyunxin.com
 * @function 创建标签
 */
public class CreateLabelActivity extends BaseActivity {

    private ArrayList<FriendEntity> arrayList = new ArrayList<FriendEntity>();
    private LabelMemberAdapter labelMemberAdapter = null;
    private MyGridView gridView;
    private Button delete_label_btn;
    private EditText label_name_et;
    private String label_name;
    private int label_id = -1;
    private View loading;
    private LabelHandle mLabelHandle = new LabelHandle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_create_label_layout;
    }

    @Override
    public void initView(View view) {
        arrayList = (ArrayList<FriendEntity>) getIntent().getSerializableExtra(
                "labelMembers");
        label_name = getIntent().getStringExtra("labelName");
        label_id = getIntent().getIntExtra("labelId", -1);
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        loading = findViewById(R.id.loading);
        delete_label_btn = (Button) findViewById(R.id.delete_label_btn);
        label_name_et = (EditText) findViewById(R.id.label_name_et);
        if (label_id == -1) {
            ((TextView) findViewById(R.id.title_textview))
                    .setText(getResources().getString(R.string.create_label));
        } else {
            ((TextView) findViewById(R.id.title_textview))
                    .setText(getResources().getString(R.string.editor_label));
            label_name_et.setText(label_name);
            label_name_et.setSelection(label_name.length());
            delete_label_btn.setVisibility(View.VISIBLE);
        }
        ((TextView) findViewById(R.id.title_right_tv)).setText(getResources()
                .getString(R.string.save));
        gridView = (MyGridView) findViewById(R.id.label_member_gv);
        findViewById(R.id.title_right_layout).setVisibility(View.VISIBLE);
    }

    protected void initListener() {
        //返回键点击
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        findViewById(R.id.title_right_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO
                        String name = label_name_et.getText().toString();
                        String custIds = getMembersCustIds();
                        if (!TextUtils.isEmpty(name)
                                && !TextUtils.isEmpty(custIds)) {
                            if (label_id != -1) {
                                updateLables(label_id, name, custIds);
                            } else {
                                createLabel(name, custIds);
                            }
                        }
                    }
                });
        delete_label_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (label_id != -1)
                    deleteLabelDailog(label_id);
            }
        });
        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                FriendEntity entity = (FriendEntity) arg0.getAdapter().getItem(
                        arg2);
                if (labelMemberAdapter.isDeleteMode()) {
                    if (entity != null && !TextUtils.isEmpty(entity.cust_id)) {
                        arrayList.remove(entity);
                        labelMemberAdapter.notifyDataSetChanged();
                    } else {
                        labelMemberAdapter.setDeleteMode(false);
                    }
                } else {
                    // TODO
                    boolean is_add = false;
                    boolean is_del = false;
                    if (arg2 == labelMemberAdapter.getCount() - 1) {
                        is_del = true;
                    } else if (arg2 == labelMemberAdapter.getCount() - 2) {
                        is_add = true;
                    }
                    if (is_del) {
                        labelMemberAdapter.setDeleteMode(true);
                    }
                    if (is_add) {
                        Intent intent = new Intent();
                        intent.setClass(CreateLabelActivity.this,
                                ChooseContactsActivity.class);
                        intent.putExtra("arraylist", arrayList);
                        intent.putExtra("isAddLabel", true);
                        startActivityForResult(intent, 100);
                    }
                }
            }
        });
    }

    private void initData() {
        if (arrayList != null) {
            labelMemberAdapter = new LabelMemberAdapter(this, arrayList);
            gridView.setAdapter(labelMemberAdapter);
        }
    }

    private String getMembersCustIds() {
        String custIds = "";
        if (arrayList != null && arrayList.size() > 0) {
            for (int i = 0, size = arrayList.size(); i < size; i++) {
                if (TextUtils.isEmpty(arrayList.get(i).cust_id)) {
                    continue;
                }
                if (TextUtils.isEmpty(custIds)) {
                    custIds = arrayList.get(i).cust_id;
                } else {
                    custIds = custIds + "," + arrayList.get(i).cust_id;
                }
            }
        }
        return custIds;
    }

    private void createLabel(String tagName, String custIds) {
        loading.setVisibility(View.VISIBLE);
        mLabelHandle.createLabel(tagName, custIds, new LabelHandle.ILabelResultListener() {

            @Override
            public void onLabelResult(int status, String msg) {
                myHandler.sendEmptyMessage(1);
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    Intent intent = new Intent(
                            BroadcastAction.LABEL_ADD_LABEL_ACTION);
                    sendBroadcast(intent);
                    finish();
                    Utils.hideSoftKeyboard(label_name_et);
                } else if (!TextUtils.isEmpty(msg)) {
                    IMApplication.showToast(msg);
                }
            }
        });

    }

    private void deleteLabelDailog(final int label_id) {
        MyDialog.Builder alertDialog = new MyDialog.Builder(
                CreateLabelActivity.this);
        alertDialog.setTitle(R.string.dialog_title);
        alertDialog.setMessage(getResources().getString(
                R.string.delete_label_dialog));
        alertDialog.setPositiveButton(R.string.yes,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteLables(label_id);
                    }
                });

        alertDialog.setNegativeButton(R.string.no,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.create().show();

    }

    private void deleteLables(final int label_id) {
        loading.setVisibility(View.VISIBLE);
        mLabelHandle.deleteLabel(label_id, new LabelHandle.ILabelResultListener() {

            @Override
            public void onLabelResult(int status, String msg) {
                myHandler.sendEmptyMessage(1);
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    setResult(RESULT_OK);
                    finish();
                    Utils.hideSoftKeyboard(label_name_et);
                } else if (!TextUtils.isEmpty(msg)) {
                    IMApplication.showToast(msg);
                }
            }
        });

    }

    /**
     * 修改标签
     *
     * @param label_id
     * @param name
     * @param custids
     */
    private void updateLables(final int label_id, String name, String custids) {
        loading.setVisibility(View.VISIBLE);
        mLabelHandle.updateLabel(label_id, name, custids,
                new LabelHandle.ILabelResultListener() {

                    @Override
                    public void onLabelResult(int status, String msg) {
                        myHandler.sendEmptyMessage(1);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            setResult(RESULT_OK);
                            finish();
                            Utils.hideSoftKeyboard(label_name_et);
                        } else if (!TextUtils.isEmpty(msg)) {
                            IMApplication.showToast(msg);
                        }
                    }
                });

    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            }

            return false;
        }
    });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        if (resultCode == RESULT_OK && requestCode == 100) {
            ArrayList<FriendEntity> entities = (ArrayList<FriendEntity>) data
                    .getSerializableExtra("labelMembers");
            arrayList.addAll(0, entities);
            labelMemberAdapter.notifyDataSetChanged();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
